package org.example.back.controller.user;

import org.example.back.entity.user.User;
import org.example.back.service.user.EmailService;
import org.example.back.service.user.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpSession;

import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private EmailService emailService;

    // 用户注册
    @PostMapping("/register")
    public Map<String, Object> register(@RequestBody User user, @RequestParam String inputCode) {
        return userService.register(user, inputCode);
    }

    // 发送验证码
    @PostMapping("/sendEmail")
    public Map<String, String> sendVerificationCode(@RequestParam String email) {
        try {
            emailService.sendVerificationCode(email);
            return Map.of("message", "验证码已发送至邮箱");
        } catch (Exception e) {
            return Map.of("error", "验证码发送失败，请稍后再试");
        }
    }

    // 登录，登录成功将 userId 存入 Session
    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody User user, HttpSession session) {
        User loginUser = userService.login(user.getEmail(), user.getPassword());
        if (loginUser != null) {
            session.setAttribute("userId", loginUser.getId());
            return Map.of("message", "登录成功",
                         "userId", loginUser.getId());
        } else {
            return Map.of("message", "邮箱或密码错误");
        }
    }

    // 登出，清空 Session
    @PostMapping("/logout")
    public Map<String, Object> logout(HttpSession session) {
        session.invalidate();
        return Map.of("message", "退出成功");
    }

    // 查询用户邮箱，从 Session 取 userId
    @GetMapping("/email")
    public Map<String, Object> getEmailByUserId(HttpSession session) {
        Integer userId = (Integer) session.getAttribute("userId");
        if (userId == null) {
            return Map.of("success", false, "message", "未登录");
        }
        String email = userService.getEmailById(userId);
        if (email != null) {
            return Map.of("success", true, "email", email);
        } else {
            return Map.of("success", false, "message", "用户不存在");
        }
    }

    // 修改用户邮箱，从 Session 取 userId
    @PutMapping("/email/update")
    public Map<String, Object> updateEmail(@RequestParam String newEmail, HttpSession session) {
        Integer userId = (Integer) session.getAttribute("userId");
        if (userId == null) {
            return Map.of("success", false, "message", "未登录");
        }
        boolean success = userService.updateEmail(userId, newEmail);
        if (success) {
            return Map.of("success", true, "message", "邮箱更新成功");
        } else {
            return Map.of("success", false, "message", "邮箱已存在或更新失败");
        }
    }

    // 查询用户名，从 Session 取 userId
    @GetMapping("/username")
    public Map<String, Object> getUsernameByUserId(HttpSession session) {
        Integer userId = (Integer) session.getAttribute("userId");
        if (userId == null) {
            return Map.of("success", false, "message", "未登录");
        }
        String username = userService.getUsernameById(userId);
        if (username != null) {
            return Map.of("success", true, "username", username);
        } else {
            return Map.of("success", false, "message", "用户不存在");
        }
    }

    // 修改用户名，从 Session 取 userId
    @PutMapping("/username/update")
    public Map<String, Object> updateUsername(@RequestParam String newUsername, HttpSession session) {
        Integer userId = (Integer) session.getAttribute("userId");
        if (userId == null) {
            return Map.of("success", false, "message", "未登录");
        }
        boolean success = userService.updateUsername(userId, newUsername);
        return success
                ? Map.of("success", true, "message", "用户名更新成功")
                : Map.of("success", false, "message", "用户名更新失败");
    }


    // 修改密码（需原密码校验）
    @PutMapping("/password/update")
    public Map<String, Object> updatePassword(@RequestParam String oldPassword,
                                          @RequestParam String newPassword,
                                          HttpSession session) {
        Integer userId = (Integer) session.getAttribute("userId");
        if (userId == null) {
            return Map.of("success", false, "message", "未登录");
        }

        boolean success = userService.updatePassword(userId, oldPassword, newPassword);
        return success
                ? Map.of("success", true, "message", "密码更新成功")
                : Map.of("success", false, "message", "原密码错误或更新失败");
}

}
